#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'bac'
import datetime
import urllib
import urllib.parse

import requests

from . import Encrypt, util


def get(url):
    """

    :param url:
    :param callback:
    :return:
    """

    url = urllib.parse.quote(url.encode('utf-8'), "'/:?&='")
    req = urllib.request.Request(url)
    res_data = urllib.request.urlopen(req)
    res = res_data.read()
    return res


def post(url, data=None):
    """

    :param url:
    :param callback:
    :return:
    """

    url = urllib.parse.quote(url.encode('utf-8'), "'/:?&='")
    # url = _fix_url(url)
    #
    headers = _singed_headers(url)

    res = requests.post(url, data, headers=headers
                        # ,proxies={"http": "http://127.0.0.1:8888","https": "https://127.0.0.1:8888"}
                        )
    return res.status_code, res.headers, res.content


def _singed_headers(url):
    if url.startswith("http://") or url.startswith("https://"):
        parts = urllib.parse.urlsplit(url)
        url = url[len(parts.scheme + '://' + parts.netloc):]

    time = _get_time_for_http()
    seed = util.random_chars(10)

    content = url + time + seed
    sign_key = 'y80htbEFR1YwZHQR47TB5ira'
    auth = Encrypt.base64_encode(Encrypt.hmac_with_sha1(sign_key, content)).rstrip("=")

    headers = {"Date": time, "X-Seed": seed, "X-Auth": auth}
    return headers


def _get_time_for_http():
    return datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')


# def _fix_url(url):
#     if url.startswith("http://") or url.startswith("https://"):
#         return url
#     return base_path + url


# def need_auth(func):
#     @functools.wraps(func)
#     def deco(*args, **kwargs):
#         auth = request.headers.get("X-Auth")
#         date = request.headers.get("Date")
#         seed = request.headers.get("X-Seed")
#         url = request.url
#         parts = urllib.parse.urlsplit(url)
#         url = url[len(parts.scheme + '://' + parts.netloc):]
#
#         if date and auth and seed:
#             content = url + date + seed
#             auth2check = Encrypt.base64_encode(Encrypt.hmac_with_sha1(sign_key, content)).rstrip("=")
#             if auth == auth2check:
#                 return func(*args, **kwargs)
#
#         return Response(response=JSON.dumps({"error": "无权访问"}), status=401, mimetype="application/json")
#
#     return deco

if __name__ == "__main__":
    pass
